<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class user_api{

	public function __construct() {
		$this->session = &load_class('Session');
		$this->initLogin();
	}

	public function initLogin(){
		if($this->isLogin()) return;
		$pz = & get_instance();
		if($remember = $pz->input->cookie(config_item('cookie_prefix').'pz_remember')){
			$this->login(str_to_arr($remember));
		}
	}

	public function forceRefreshLoginInfo(){
		if($this->isLogin()){
			$user = $this->getUserByid($this->session->get('uid'));
			$this->setsession($user);
		}
	}

	public function getUserInfo(){
		return $this->session->all();
	}

	public function isLogin(){
		return ($this->session->get('uid')) ? $this->session->get('uid') : FALSE;
	}

	public function isAdmin(){
		return ($this->session->get('system')==1) ? TRUE : FALSE;
	}

	public function isEditor(){
		return ($this->session->get('system')==2) ? TRUE : FALSE;
	}

	public function isBP(){
		return ($this->session->get('system')==4) ? TRUE : FALSE;
	}

	public function isBV(){
		return ($this->session->get('system')==3) ? TRUE : FALSE;
	}
	public function getUsers($page,$pagesize){
		return load_db('user')->search($page,$pagesize);
	}

	public function adminSearchUsers($condition,$page,$pagesize){
		$sort = " ptx_user.create_time DESC ";
		$users = load_db('user')->search($condition,$page,$pagesize,'',$sort);
		$user2usergroupDB = load_db('user/user2usergroup');
		foreach ($users as $key=>$user){
			$groups = $user2usergroupDB->getGroupsDetailByUser($user['user_id'],' usergroup.usergroup_type,usergroup.usergroup_name ');
			foreach ($groups as $g){
				$users[$key][$g['usergroup_type']] = $g['usergroup_name'];
			}
		}
		return $users;
	}
	public function updateCredits($rule,$user_id){
		$setting = load_api('setting')->getSetting('credit');
		$credit_formula_exe = $setting['credit_formula_exe'];
		if($credit_formula_exe){
			$user_data = $this->getUserByid($user_id);
			$total_followers = $user_data['total_follower'];
			$total_likes = $user_data['total_like'];
			$total_shares = $user_data['total_share'];
			$ext_credits_1 = $user_data['ext_credits_1']+$rule['ext_credits_1'];
			$ext_credits_2 = $user_data['ext_credits_2']+$rule['ext_credits_2'];
			$ext_credits_3 = $user_data['ext_credits_3']+$rule['ext_credits_3'];
			eval("\$rule['credits']=$credit_formula_exe;");
			load_db('user')->updateCredits($rule,$user_id);
			$this->refreshGroup($rule['credits'],$user_id);
		}
	}

	public function refreshGroup($credits,$user_id){
		$user = $this->getUserInfo();
		$usergroupapi = load_api('user/usergroup');
		$memgroups = $usergroupapi->getMemberUserGroup();

		$memg = $memgroups[$user['member']];
		if(($memg&&($credits>$memg['credits_higher']||$credits<$memg['credits_lower']))||!$memg){
			foreach ($memgroups as $group){
				if($credits>=$group['credits_lower']&&$credits<=$group['credits_higher']){
					load_db('user/user2usergroup')->updateUserGroup($user_id,$group['usergroup_id'],'member');
					$user['member'] = $group['usergroup_id'];
					$this->fillsessiondata($user);
					return;
				}
			}
		}
	}

	public function getUserWithGroupByid($id){
		$user = $this->getUserByid($id);
		$groups = load_db('user/user2usergroup')->getGroupsDetailByUser($user['user_id'],' usergroup.usergroup_type,usergroup.usergroup_key,usergroup.usergroup_name ');
		foreach ($groups as $group){
			$user[$group['usergroup_type']] = $group;
		}
		return $user;
	}

	public function updateUserGroup($uid,$sysgid,$memgid,$spegid){
		$user2usergroupDB = load_db('user/user2usergroup');
		if($sysgid){
			$user2usergroupDB->updateUserGroup($uid,$sysgid,'system');
		}
		if($memgid){
			$user2usergroupDB->updateUserGroup($uid,$memgid,'member');
		}
		if($spegid){
			$user2usergroupDB->updateUserGroup($uid,$spegid,'special');
		}
	}
	
	public function updateUserSystemGroupVerify($uid){
		$user2usergroupDB = load_db('user/user2usergroup');
		$user2usergroupDB->updateUserGroup($uid,5,'system');
	}
	public function updateUserSystemGroupMember($uid){
		$user2usergroupDB = load_db('user/user2usergroup');
		$user2usergroupDB->updateUserGroup($uid,6,'system');
	}
	public function updateUserSystemGroupBP($uid){
		$api = load_api('user/usergroup');
		$group = $api->getGroupByKey('banned_post','system');
		if($group){
			$user2usergroupDB = load_db('user/user2usergroup');
			$user2usergroupDB->updateUserGroup($uid,$group['usergroup_id'],'system');
		}
	}
	public function updateUserSystemGroupBV($uid){
		$api = load_api('user/usergroup');
		$group = $api->getGroupByKey('banned_visit','system');
		if($group){
			$user2usergroupDB = load_db('user/user2usergroup');
			$user2usergroupDB->updateUserGroup($uid,$group['usergroup_id'],'system');
		}
	}

	public function deleteUserByid($id){
		$userdb = load_db('user');
		$user = $this->getUserByid($id);
		$condition = array('user_id'=>$id);
		$result = $userdb->delete($condition);
		if($result) {
			load_db('event/activity')->deleteByUser($id);
			load_api('album')->deleteByUser($id);
			load_db('album/favalbum')->delete($condition);
			load_db('share/favshare')->delete($condition);
			load_db('comment')->delete($condition);
			load_db('social/connector')->delete($condition);
		}
		return $result;
	}

	public function getUserByid($id){
		return load_db('user')->findJoin(array('user_id'=>$id));
	}
	public function getUserByEmail($email){
		return load_db('user')->findJoin(array('email'=>$email));
	}
	public function getUserByNick($nick){
		return load_db('user')->findJoin(array('nickname'=>$nick));
	}
	public function getUserByDomain($domain){
		return load_db('user')->findJoin(array('domain'=>$domain));
	}
	public function getUIDSByUnameArray($name_arr){
		return load_db('user')->find_userid_by_uname($name_arr);
	}

	public function updateUserByid($id,$update){
		return load_db('user')->update(array('user_id'=>$id),$update);;
	}

	public function addAlbum($uid){
		$userdb = load_db('user');
		return $userdb->add_album($uid);
	}

	public function delAlbum($uid){
		$userdb = load_db('user');
		return $userdb->del_album($uid);
	}

	//501 password wrong 502 user not existed.
	public function login($data){
		$userdb = load_db('user');
		$user = $userdb->find(array('email'=>$data['email']));
		if($user){
			if( $user['passwd'] === md5($data['password'])){
				$user['password'] = $data['password'];
				$user['remember'] = $data['remember'];
				$this->setsession($user);
				$ucopen = config_item('UC_OPEN','uc');
				if($ucopen){
					$this->loginuc($user);
				}
				$userdb->updateField(array('email'=>$data['email']), 'last_login_time', TIMESTAMP);
				load_api('event')->daylogin($user['user_id']);
				return TRUE;
			}else {
				return 501;
			}
		}else{
			return 502;
		}
	}

	public function resetpasswd($userid,$password){
		$userdb = load_db('user');
		$result = $userdb->update(array('user_id'=>$userid), array('passwd'=>md5($password)));
		if($result){
			$ucopen = config_item('UC_OPEN','uc');
			if($ucopen){
				$ucenter = load_api('ucenter');
				$user = $this->getUserByid($userid);
				if($user['uc_id']){
					$ucenter->uc_user_edit($user['nickname'],null, $password, null,1);
				}
			}
		}
		return $result;
	}

	//500 notopen 501 password wrong 502 user not existed.
	public function bbs_login($data){
		$userdb = load_db('user');
		$uc_password = $data['bbs_password'];
		$uc_username = strtolower($data['bbs_username']);
		$ucopen = config_item('UC_OPEN','uc');
		if($ucopen){
			$ucenter = load_api('ucenter');
			list($uid, $username, $password, $email)=$ucenter->uc_user_login($uc_username, $uc_password);
			if($uid == -1) {
				return 502;
			}elseif ($uid == -2){
				return 501;
			}elseif ($uid>0){
				if($user = $userdb->find_by_ucid($uid)){
					$user['password'] = $uc_password;
					$user['remember'] = $data['remember'];
					$this->setsession($user);
				}else{
					$user_data['email'] = ($userdb->checkemail($email))?$email:md5(uniqid(mt_rand())).'@'.config_item('default_domain');
					$user_data['nickname'] = $userdb->create_random_nick($username);
					$user_data['passwd'] = md5($uc_password);
					$user_data['create_time'] = TIMESTAMP;
					$user_data['is_active'] = 1;
					$user_data['is_social'] = 0;
					$user_data['uc_id'] = $uid;
					$user_data['uc_nickname'] = $uc_username;
					$user_id = $userdb->add_one($user_data);
					load_helper('view');
					create_default_avatar($user_id);
					$user = $userdb->getuser_byid($user_id);
					$user['password'] = $uc_password;
					$this->setsession($user);
				}
				$synlogin_str = $ucenter->uc_user_synlogin($uid);
				return $synlogin_str;
			}
		}
		return 500;
	}

	public function logout(){
		$this->removesession();
		if(config_item('UC_OPEN','uc')){
			$ucenter = load_api('ucenter');
			$synlogout_str = $ucenter->uc_user_synlogout();
			return $synlogout_str;
		}
	}

	public function adminlogin($data){
		$userdb = load_db('user');
		$user = $userdb->find(array('email'=>$data['email']));
		if($user){
			if( $user['passwd'] === md5($data['password'])){
				$user['password'] = $data['password'];
				$user['remember'] = $data['remember'];
				$groups = $this->getGroupsByUser($user['user_id']);
				if($groups['system']==1){
					$this->setsession($user);
					return TRUE;
				}else{
					return FALSE;
				}
			}
		}
		return FALSE;
	}

	private function loginuc($user){
		$userdb = load_db('user');
		$ucenter = load_api('ucenter');
		$uc_password = $user['password'];
		$uc_username = ($user['uc_nickname'])?strtolower($user['uc_nickname']):strtolower($user['nickname']);
		list($uid, $username, $password, $email)=$ucenter->uc_user_login($uc_username, $uc_password);
		if($uid == -1) {
			$reg_uid = $ucenter->uc_user_register($uc_username, $uc_password, $data['email']);
			if($reg_uid>0){
				$data['uc_nickname'] = $uc_username;
				$data['uc_id'] = $reg_uid;
				$userdb->update(array('user_id'=>$user['user_id']), $data);
			}
		}elseif ($uid>0){
			$synlogin_str = $ucenter->uc_user_synlogin($uid);
			if(!$user['uc_id'])
				$userdb->updateUCID($user, $uid, $username);
		}
	}

	public function getGroupsByUser($uid,$usergroups=array()){
		$groups = load_db('user/user2usergroup')->getGroupsByUser($uid);
		foreach ($groups as $group){
			$usergroups[$group['usergroup_type']] = $group['usergroup_id'];
		}
		return $usergroups;
	}


	public function setsession($user){
		$userdata = array('uid'=>$user['user_id'],'nickname'=>$user['nickname'],'email'=>$user['email'],'isstar'=>$user['is_star'],'issocial'=>$user['is_social'],
				'ucid'=>$user['uc_id'],'ucname'=>$user['uc_nickname'],'password'=>$user['password'],'remember'=>$user['remember']);
		/* $groups = load_db('user/user2usergroup')->getGroupsByUser($user['user_id']);
		 foreach ($groups as $group){
		$userdata[$group['usergroup_type']] = $group['usergroup_id'];
		} */
		$userdata = $this->getGroupsByUser($user['user_id'],$userdata);
		$this->fillsessiondata($userdata);
	}

	public function fillsessiondata($userdata){
		$session = &load_class('Session');
		$session->put($userdata);
		if($userdata['remember']){
			$remember['email'] = $userdata['email'];
			$remember['password'] = $userdata['password'];
			$remember['remember'] = $userdata['remember'];
			$IN	=& load_class('Input', 'core');
			$IN->set_cookie('pz_remember', array_to_str($remember), 86400*365);
		}
	}

	public function removesession(){
		$session = &load_class('Session');
		$session->sess_destroy();
		$IN	=& load_class('Input', 'core');
		$IN->set_cookie('pz_remember', '', '');
	}

	public function synlogin($uc_id){
		$userdb = load_db('user');
		log_message('debug',"user api synlogin=".$uc_id);
		if($user = $userdb->find_by_ucid($uc_id)){
			$this->setsession($user);
		}
	}

	public function updateLike($uid,$count){
		//return load_db('user')->updateLike($uid,$count);
		return load_db('user')->updateField(array('user_id'=>$uid),'total_like',$count);
	}

	public function updateFavShareNum($uid,$count){
		return load_db('user')->updateField(array('user_id'=>$uid),'total_favorite_share',$count);
	}
}
